from ivic.core import Config, project_path
from ivic.core import Logging
from ivic.vspace.Server import  *
from ivic.vspace.ServerMonitor import *
from ivic.vspace.Config import  *

logger = Logging.get_logger('ivic.vspace.Plugin')

__obj = None
__VSpaceTracker = None
__VSpaceRePorter = None
__VSpaceServerMonitor = None

def init(daemon_config):
    config = Config.load(project_path('/etc/ivic/vspace.yaml'))
    # this should dispatch 'ivic.vspace.*' to individual log file??? don't understat, gengjp, 0427
    # vmcweb shares the same log file with vmc???
    Logging.get_logger('ivic.vspace.Plugin', filename = config['log_file'])
    Logging.get_logger('ivic.vspace.VSpace', filename = config['log_file'])
    Logging.get_logger('ivic.vspace.Server', filename = config['log_file'])
    Logging.get_logger('ivic.vspace.ServerMonitor', filename=config['log_file'])

    logger.debug('initializing %s' % __name__)
    global __obj
    if __obj:
        logger.error('reinitialized is not supported')
        return

    __obj = VSpaceServer(config)
    
    global __VSpaceTracker
    if __VSpaceTracker:
        logger.error('[Tracker]reinitialized is not supported')
        return
    
    __VSpaceTracker = VSpaceTracker(__obj)
    __VSpaceTracker.start()
    
    portal = vspace_config.portal_url 
    if portal[-1] != '/':
        portal = portal + "/"
        
#*****************************************************************************    
    global __VSpaceServerMonitor
    if __VSpaceServerMonitor:
        logger.error('[Tracker]reinitialized is not supported')
        return
    try:
        server_url = None
        try:
            server_url = portal
            if server_url != None:
                server_url = server_url + 'vsaasmonitor/update_status'
        except Exception, e:
            logger.error('%s' % e)
            
        __VSpaceServerMonitor = ServerMonitor(server_url,'linux-vspace')
        __VSpaceServerMonitor.start()
        __obj.setServerMonitor(__VSpaceServerMonitor)
    except Exception, e:
        logger.error('%s' % e)
#*****************************************************************************

    global __VSpaceRePorter
    if __VSpaceRePorter:
        logger.error('[Tracker]reinitialized is not supported')
        return
    
    try:
        url = portal + "vspace/"
    except Exception,e:
        url = None
        
    __VSpaceRePorter = Singleton.Reporter(url)
    __VSpaceRePorter.start()
    
def fini():
    global __obj 
    del __obj

def soap_mods():
    global __obj
    return {'/vspace': __obj}

def wsgi_mods():        
    return {}
